import { createSlice } from '@reduxjs/toolkit'

interface DeviceState {
  devices: any[]
  loading: boolean
  error: string | null
}

const initialState: DeviceState = {
  devices: [],
  loading: false,
  error: null,
}

const deviceSlice = createSlice({
  name: 'device',
  initialState,
  reducers: {
    setDevices: (state, action) => {
      state.devices = action.payload
    },
    addDevice: (state, action) => {
      state.devices.push(action.payload)
    },
    updateDevice: (state, action) => {
      const index = state.devices.findIndex(d => d.id === action.payload.id)
      if (index !== -1) {
        state.devices[index] = { ...state.devices[index], ...action.payload }
      }
    },
    removeDevice: (state, action) => {
      state.devices = state.devices.filter(d => d.id !== action.payload)
    },
  },
})

export const { setDevices, addDevice, updateDevice, removeDevice } = deviceSlice.actions
export default deviceSlice.reducer

